#include <stdio.h>
#include <sys/ioctl.h>
#include <strings.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#include "time_treatement.h"


/**********************acquisition de l'IP de l'host*******************/

char * my_ipaddr()
{


	int sock = socket(PF_INET, SOCK_STREAM,0);
	if(sock <0 ) 
	{
		perror("Erreur de la creation de la socket \n" );
		exit(1);
	}

	u_int32_t nip;
	getIP(sock,"wlan0",&nip);

	struct in_addr in;
	in.s_addr = nip;
	char * cip =  inet_ntoa( in );

	//printf("my IP: %s\n",cip);

	return cip;
}

int getIP(int fd, char * ifname,  u_int32_t * ipaddr) 
{

	struct ifreq
	{
		char ifr_name[16];
		struct sockaddr ifr_addr;
	};

	struct ifreq ifr;
	memcpy(ifr.ifr_name, ifname, 16);

	if(ioctl(fd, SIOCGIFADDR, &ifr) == -1)
	{
		perror("getIP: ioctl" );
		exit(-1);
	}

	memcpy(ipaddr, &ifr.ifr_addr.sa_data[2], 4);
	return 0;
}


	 


		/********************copy*****************/

void copy_log (FILE * src, FILE* des, int a)
{
	char * buffer=(char*)calloc(800, sizeof(char));
	char * ip;
	ip=my_ipaddr();
	char * found;
	fgets (buffer, 800, src);
	while (!feof(src))
	{
		if ((found=strstr(buffer, "<"))!=NULL)
		{
			if (strstr(buffer, ip)==NULL)
			{
				int tmp=0;
				tmp=difference_now(time_read(buffer));
				printf ("Le temps écoulé depuis l'acquisition : %i secondes \n\n", tmp);
				if (tmp>a)
				{
					//processus de Copie
					fputs (buffer, des);
					while(strstr(buffer, "<")!=NULL)
					{
						fgets (buffer, 800, src);
						fputs (buffer, des);

					}
					fgets (buffer, 800, src);
					fputs(buffer, des);
				}
				else
				{
					fgets (buffer, 800, src);
				}
			}
			else
			{
				fgets (buffer, 800, src);
			}
		}
		else
		{
			fgets (buffer, 800, src);
		}
	}
}
